package com.cosmoplat.gfqd.processor;

import com.cosmoplat.gfqd.config.BootStrapConfig;
import com.cosmoplat.gfqd.constants.Constants;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 创建pom.xml到clone的项目中
 * 用于构建模板项目
 */
public class CreatePomXMLFile {

    private static String ARCHETYPE_PACKAGE;
    private static String ARCHETYPE_ARTIFACTID;
    private static String ARCHETYPE_VERSION;

    public static void create(BootStrapConfig config) {

        if (config != null) {
            System.out.println("Loaded bootstrap: " + config);
            // Access config values
            ARCHETYPE_PACKAGE = config.getCreateProject().getArchetypePackage();
            ARCHETYPE_ARTIFACTID = config.getCreateProject().getArchetypeArtifactId();
            ARCHETYPE_VERSION = config.getCreateProject().getArchetypeVersion();
        }

        try {
            // 指定输出路径
            String outputPath = Constants.GITLAB_PROJECTS +"/"+ Constants.POM_XML_FILE;
            Path targetDirectory = Paths.get(Constants.GITLAB_PROJECTS);
            // 示例的项目名称列表
            List<String> projectNames = getProjectNamesFromDirectory(targetDirectory);

            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.newDocument();

            // 设置根元素 <project>
            Element project = doc.createElement("project");
            project.setAttribute("xmlns", "http://maven.apache.org/POM/4.0.0");
            project.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
            project.setAttribute("xsi:schemaLocation", "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd");
            doc.appendChild(project);

            // <modelVersion>
            Element modelVersion = doc.createElement("modelVersion");
            modelVersion.appendChild(doc.createTextNode("4.0.0"));
            project.appendChild(modelVersion);

            // <groupId>, <artifactId>, <version>, <packaging>
            Element groupId = doc.createElement("groupId");
            groupId.appendChild(doc.createTextNode(ARCHETYPE_PACKAGE));
            project.appendChild(groupId);

            Element artifactId = doc.createElement("artifactId");
            artifactId.appendChild(doc.createTextNode(ARCHETYPE_ARTIFACTID));
            project.appendChild(artifactId);

            Element version = doc.createElement("version");
            version.appendChild(doc.createTextNode(ARCHETYPE_VERSION));
            project.appendChild(version);

            Element packaging = doc.createElement("packaging");
            packaging.appendChild(doc.createTextNode("pom"));
            project.appendChild(packaging);

            // <parent>
            Element parent = doc.createElement("parent");
            Element parentArtifactId = doc.createElement("artifactId");
            parentArtifactId.appendChild(doc.createTextNode("cosmoplat-gfqd-bom"));
            parent.appendChild(parentArtifactId);

            Element parentGroupId = doc.createElement("groupId");
            parentGroupId.appendChild(doc.createTextNode("com.cosmoplat.gfqd"));
            parent.appendChild(parentGroupId);

            Element parentVersion = doc.createElement("version");
            parentVersion.appendChild(doc.createTextNode("1.0.0-SNAPSHOT"));
            parent.appendChild(parentVersion);
            project.appendChild(parent);

            // 在 <parent> 后添加 <modules>
            Element modules = doc.createElement("modules");
            for (String projectName : projectNames) {
                Element module = doc.createElement("module");
                module.appendChild(doc.createTextNode(projectName));
                modules.appendChild(module);
            }
            project.appendChild(modules);

            // <properties>
            Element properties = doc.createElement("properties");

            Element mavenCompilerSource = doc.createElement("maven.compiler.source");
            mavenCompilerSource.appendChild(doc.createTextNode("8"));
            properties.appendChild(mavenCompilerSource);

            Element mavenCompilerTarget = doc.createElement("maven.compiler.target");
            mavenCompilerTarget.appendChild(doc.createTextNode("8"));
            properties.appendChild(mavenCompilerTarget);

            Element projectBuildSourceEncoding = doc.createElement("project.build.sourceEncoding");
            projectBuildSourceEncoding.appendChild(doc.createTextNode("UTF-8"));
            properties.appendChild(projectBuildSourceEncoding);

            project.appendChild(properties);

            // <build>
            Element build = doc.createElement("build");
            Element plugins = doc.createElement("plugins");
            Element plugin = doc.createElement("plugin");

            Element pluginGroupId = doc.createElement("groupId");
            pluginGroupId.appendChild(doc.createTextNode("org.apache.maven.plugins"));
            plugin.appendChild(pluginGroupId);

            Element pluginArtifactId = doc.createElement("artifactId");
            pluginArtifactId.appendChild(doc.createTextNode("maven-archetype-plugin"));
            plugin.appendChild(pluginArtifactId);

            Element pluginVersion = doc.createElement("version");
            pluginVersion.appendChild(doc.createTextNode("3.0.0"));
            plugin.appendChild(pluginVersion);

            Element configuration = doc.createElement("configuration");
            Element propertyFile = doc.createElement("propertyFile");
            propertyFile.appendChild(doc.createTextNode("./archetype.properties"));
            configuration.appendChild(propertyFile);
            plugin.appendChild(configuration);

            plugins.appendChild(plugin);
            build.appendChild(plugins);
            project.appendChild(build);

            // 将内容写入 XML 文件,设置 Transformer 属性，去掉 standalone 属性!!!!!
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); // 设置缩进为 4 个空格
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(outputPath));
            transformer.transform(source, result);

            System.out.println("XML 文件已生成并保存到指定路径：" + outputPath);

        } catch (ParserConfigurationException | javax.xml.transform.TransformerException | IOException e) {
            e.printStackTrace();
        }
    }

    // 获取目标目录下所有项目名的方法
    private static List<String> getProjectNamesFromDirectory(Path directory) throws IOException {
        return Files.list(directory)
                .filter(Files::isDirectory)
                .map(Path::getFileName)
                .map(Path::toString)
                .filter(name -> !name.equals("target")) // 过滤掉 target 目录
                .collect(Collectors.toList());
    }
}